package util

import (
	"context"
	"fmt"
	"os"
	"os/signal"
	"syscall"
)

// ListenQuitSignal 监听退出信号
func ListenQuitSignal(ctx context.Context, done func()) {
	// 创建信号通道
	sigs := make(chan os.Signal, 1)
	signal.Notify(sigs, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)

	// 监听信号或者上下文
	select {
	case <-sigs:
	case <-ctx.Done():
	}

	// 退出前执行函数
	done()
}

const (
	SIZE_KB = 1024
	SIZE_MB = 1024 * SIZE_KB
	SIZE_GB = 1024 * SIZE_MB
	SIZE_TB = 1024 * SIZE_GB
	SIZE_PB = 1024 * SIZE_TB
)

// FormatBytesToString 格式化数据大小
//
// 如：123456789 -> 117.738MB
func FormatBytesToString(size int64) string {
	switch {
	case size < SIZE_KB:
		return fmt.Sprintf("%.3fB", float64(size))
	case size < SIZE_MB:
		return fmt.Sprintf("%.3fKB", float64(size)/float64(SIZE_KB))
	case size < SIZE_GB:
		return fmt.Sprintf("%.3fMB", float64(size)/float64(SIZE_MB))
	case size < SIZE_TB:
		return fmt.Sprintf("%.3fGB", float64(size)/float64(SIZE_GB))
	case size < SIZE_PB:
		return fmt.Sprintf("%.3fTB", float64(size)/float64(SIZE_TB))
	default:
		return fmt.Sprintf("%.3fPB", float64(size)/float64(SIZE_PB))
	}
}
